import { useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Layout } from 'antd';

// 页面组件
import HomePage from '@/pages/Home';
import SearchPage from '@/pages/Search';
import ProfilePage from '@/pages/Profile';
import AnalyticsPage from '@/pages/Analytics';
import NotFoundPage from '@/pages/NotFound';

// 布局组件
import { MainLayout } from '@/components/layout/MainLayout';
import { Header } from '@/components/layout/Header';
import { Footer } from '@/components/layout/Footer';

// Hooks
import { useAppStore, useAppActions } from '@/stores';

// 样式
import './App.css';

const { Content } = Layout;

/**
 * 主应用组件
 */
function App() {
  const { theme, isOnline, globalError } = useAppStore(state => ({
    theme: state.theme,
    isOnline: state.isOnline,
    globalError: state.globalError,
  }));
  
  const { setOnlineStatus, setDeviceType, updateLastActivity } = useAppActions();

  // 初始化应用
  useEffect(() => {
    // 检测设备类型
    const detectDeviceType = () => {
      const width = window.innerWidth;
      if (width < 768) {
        setDeviceType('mobile');
      } else if (width < 1024) {
        setDeviceType('tablet');
      } else {
        setDeviceType('desktop');
      }
    };

    // 监听窗口大小变化
    const handleResize = () => {
      detectDeviceType();
    };

    // 监听网络状态变化
    const handleOnline = () => setOnlineStatus(true);
    const handleOffline = () => setOnlineStatus(false);

    // 监听用户活动
    const handleUserActivity = () => updateLastActivity();

    // 初始检测
    detectDeviceType();
    setOnlineStatus(navigator.onLine);

    // 添加事件监听器
    window.addEventListener('resize', handleResize);
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    
    // 用户活动监听
    const activityEvents = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
    activityEvents.forEach(event => {
      document.addEventListener(event, handleUserActivity, { passive: true });
    });

    // 清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
      
      activityEvents.forEach(event => {
        document.removeEventListener(event, handleUserActivity);
      });
    };
  }, [setDeviceType, setOnlineStatus, updateLastActivity]);

  // 应用主题类名
  const appClassName = `app ${theme === 'dark' ? 'dark' : ''}`;

  return (
    <div className={appClassName}>
      <Layout className="min-h-screen">
        {/* 页头 */}
        <Header />
        
        {/* 主内容区域 */}
        <Content className="flex-1">
          <MainLayout>
            {/* 离线提示 */}
            {!isOnline && (
              <div className="bg-yellow-50 dark:bg-yellow-900/20 border-l-4 border-yellow-400 p-4 mb-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <svg
                      className="h-5 w-5 text-yellow-400"
                      viewBox="0 0 20 20"
                      fill="currentColor"
                    >
                      <path
                        fillRule="evenodd"
                        d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                        clipRule="evenodd"
                      />
                    </svg>
                  </div>
                  <div className="ml-3">
                    <p className="text-sm text-yellow-700 dark:text-yellow-200">
                      您当前处于离线状态。某些功能可能无法正常使用。
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* 全局错误提示 */}
            {globalError && (
              <div className="bg-red-50 dark:bg-red-900/20 border-l-4 border-red-400 p-4 mb-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <svg
                      className="h-5 w-5 text-red-400"
                      viewBox="0 0 20 20"
                      fill="currentColor"
                    >
                      <path
                        fillRule="evenodd"
                        d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                        clipRule="evenodd"
                      />
                    </svg>
                  </div>
                  <div className="ml-3">
                    <p className="text-sm text-red-700 dark:text-red-200">
                      {globalError}
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* 路由配置 */}
            <Routes>
              {/* 首页 */}
              <Route path="/" element={<HomePage />} />
              
              {/* 搜索页面 */}
              <Route path="/search" element={<SearchPage />} />
              
              {/* 用户个人页面 */}
              <Route path="/profile" element={<ProfilePage />} />
              
              {/* 数据分析页面 */}
              <Route path="/analytics" element={<AnalyticsPage />} />
              
              {/* 404 页面 */}
              <Route path="/404" element={<NotFoundPage />} />
              
              {/* 重定向到 404 */}
              <Route path="*" element={<Navigate to="/404" replace />} />
            </Routes>
          </MainLayout>
        </Content>
        
        {/* 页脚 */}
        <Footer />
      </Layout>
    </div>
  );
}

export default App;
